package com.atguigu.gulimall.product;

import lombok.SneakyThrows;

/**
 * 3个线程交替运行
 */
public class ThreadDemoTwo {

    public static void main(String[] args) {
        ThreadDemoTwo.print p = new ThreadDemoTwo.print();
        new Thread(){
            @SneakyThrows
            public void run(){
                while (true)
                    p.print1();
            }
        }.start();

        new Thread(){
            @SneakyThrows
            public void run(){
                while (true)
                    p.print2();
            }
        }.start();

        new Thread(){
            @SneakyThrows
            public void run(){
                while (true)
                    p.print3();
            }
        }.start();
    }

    static class print{
        int flag = 1;
        public void print1() throws InterruptedException {
            synchronized (this){
                while(flag != 1){
                    this.wait();
                }
                System.out.println("1111");
                flag = 2;
                this.notifyAll();
            }
        }

        public void print2() throws InterruptedException {
            synchronized (this) {
                while (flag != 2) {
                    this.wait();
                }
                System.out.println("2222");
                flag = 3;
                this.notifyAll();
            }
        }

        public void print3() throws InterruptedException {
            synchronized (this) {
                while (flag != 3) {
                    this.wait();
                }
                System.out.println("3333");
                flag = 1;
                this.notifyAll();
            }
        }
    }

}
